<template>
  <div id="app">
    <RouterView v-if="isShow" v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" />
      </transition>
    </RouterView>
  </div>
</template>

<script>
import { RouterView } from 'vue-router'
import { LoginUrl,HttpUrl, ERR_OK } from 'api/config'
import { ajaxPostFormData } from 'api/axios'
import { getUrlParam } from 'common/js/utils'
import { setStorage, getStorage, removeStorage } from 'common/js/utils'
import { tokenStorageKey, userInfoStorageKey, mapTokenStorageKey } from 'common/js/config'

export default {
  components: {
    RouterView
  },
  created () {
    this.initUser()
  },
  data () {
    return {
      isShow: false
    }
  },
  methods: {
    async initUser () {
      const token = getUrlParam('access_token')

      if (!token) {
        removeStorage(tokenStorageKey)
        removeStorage(userInfoStorageKey)
        removeStorage(mapTokenStorageKey)
        console.log('无access_token')
        // window.location.href = LoginUrl
        return
      }
      
      const tokenStorage = getStorage(tokenStorageKey)

      if (
        !tokenStorage ||
        (tokenStorage && token !== tokenStorage.token) || 
        (new Date().getTime() - tokenStorage.createTime >= 1000 * 60 * 60 * 12)
      ) {
        setStorage(tokenStorageKey, { token, createTime: new Date().getTime() })
        removeStorage(userInfoStorageKey)
      }

      const userInfo = getStorage(userInfoStorageKey)
      
      if (!userInfo) {
        const res = await ajaxPostFormData(`${HttpUrl}/checkUser/token`)
          
        if (res.code === ERR_OK) {
          setStorage(userInfoStorageKey, res.data)
          this.isShow = true
        } else {
          removeStorage(tokenStorageKey)
          removeStorage(userInfoStorageKey)
          removeStorage(mapTokenStorageKey)
          console.log('token过期')
          // window.location.href = LoginUrl
        }
      } else {
        this.isShow = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>